﻿package tools;

import java.util.ArrayList;

/**
 * 给定一组有序词语，输出其N-gram
 * @author Lanjun
 *
 */
public class Ngram {

	/**
	 * 输出对应的N-gram
	 * @param words 给定的有序序列
	 * @param N N的值，小于2的时候将直接返回原始序列
	 * @return 可能的N-gram
	 */
	public static ArrayList<String> getNgrams(ArrayList<String> words, int N) {
		if (N <= 1) {
			return words;
		}

		if (N > 1) {
			ArrayList<String> output = new ArrayList<String>();
			for (int i = 0; i < (words.size() - N + 1); i++) {
				StringBuilder ngram = new StringBuilder();
				for (int j = i; j < (i + N); j++) {
					ngram.append(words.get(j));
					if (j != (i + N - 1)) {
						ngram.append(' ');
					}
				}
				output.add(ngram.toString());
			}
			return output;
		}
		return null;
	}

	public static void main(String[] args) {
		ArrayList<String> words = new ArrayList<String>();
		words.add("aa");
		words.add("bb");
		words.add("cc");
		words.add("dd");
		words.add("ee");
		words.add(".");

		System.out.println(Ngram.getNgrams(words, 2));
		System.out.println(Ngram.getNgrams(words, 3));
		System.out.println(Ngram.getNgrams(words, 4));
	}

}
